from PyQt4 import QtGui, QtCore
import db
import sys
from datetime import date
import query
import AddPlan

class TLogin (QtGui.QWidget):

    def __init__(self,AppManObj, parent = None):
        QtGui.QWidget.__init__(self, parent)
        self.app_man_obj = AppManObj
        self.pass_label = QtGui.QLabel("Enter your password here:")
        self.pass_edit = QtGui.QLineEdit("")
        self.btnLogin = QtGui.QPushButton("Login")
        self.login_edit = QtGui.QLineEdit("")
        self.login_label = QtGui.QLabel("Enter your login here:")
        self.warning_label = QtGui.QLabel("Pass or login you've entered is incorrect")
        self.warning_label.setVisible(False)
        #self.login_edit.setInputMask(translatable, "*")
        self.pass_edit.setEchoMode(QtGui.QLineEdit.Password)
        self.vbox = QtGui.QVBoxLayout()
        self.vbox.addWidget(self.warning_label)
        self.vbox.addWidget(self.login_label)
        self.vbox.addWidget(self.login_edit)
        self.vbox.addWidget(self.pass_label)
        self.vbox.addWidget(self.pass_edit)
        self.vbox.addWidget(self.btnLogin)
        self.setLayout(self.vbox)
        self.passwd = self.pass_edit.text()
        self.move(400, 300)
        self.connect(self.btnLogin, QtCore.SIGNAL("clicked()"), self.login_to_db)
        #self.connect(self.)
        self.connect(self.pass_edit, QtCore.SIGNAL("returnPressed()"), self.login_to_db)
        self.connect(self.login_edit, QtCore.SIGNAL("returnPressed()"), self.login_to_db)

    def login_to_db (self):
        self.db_session = db.SQLSession(str(self.login_edit.text()), str(self.pass_edit.text()), 'localhost')
        if self.db_session.db_connect():
            #self.app_man_obj.close_window()
            app_man_obj.db_session = self.db_session
            self.app_man_obj.show_main()
        else:
            self.warning_label.setVisible(True)

    def mask_input (self):
        text = self.pass_edit.text()
        self.passwd = self.passwd + text[len(text)-1]
        self.pass_edit.setText(str(text[0:len(text)-1]) + '*')
        print 'text ', self.passwd

class AppManager:
    def __init__ (self, app):
        self.app = app
        self.db_session = None

    def show_login (self):
        self.window = TLogin(self)
        self.window.setWindowTitle("Please login to the app")
        self.window.resize(300, 100)
        self.window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
        self.window.show()

    def show_commit_update(self, parent_dictionary):
        self.commit_window = UpdateCommitWindow(self, parent_dictionary, self.main_window)
        self.commit_window.setWindowTitle("Change commit")
        self.commit_window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
        print "update commit entered"
        self.commit_window.resize(700, 400)
        self.commit_window.show()

    def show_commit_planning(self, parent_dictionary):
        self.commit_planning_window = AddPlan.CommitPlanningWindow(
            self, parent_dictionary, self.main_window
            )
        self.commit_planning_window.setWindowTitle("Change commit")
        self.commit_planning_window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
        print "update commit entered"
        self.commit_planning_window.resize(700, 400)
        self.commit_planning_window.show()

    def close_window (self):
        self.window.close()

    def close_commit (self):
        self.commit_window.close()

    def show_main (self):
        self.main_window = QtGui.QWidget()
        self.main_window = MainForm(self)
        self.window.close()
        self.main_window.setWindowTitle("Dash home")
        #print "passed - 2"
        self.main_window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
        self.main_window.resize(1024, 800)
        self.main_window.show()
        #self.window.update_dashboard()

    def show_commit (self):
        self.commit_window = CommitWindow(self, self.main_window)
        self.commit_window.setWindowTitle("Commit")
        self.commit_window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
        #print "passed - 4"
        self.commit_window.resize(700, 400)
        self.commit_window.show()

    def show_add_idea_window (self):
        self.idea_window = AddPlan.AddPlanWindow (self, self.main_window)
        self.idea_window.setWindowTitle("Add to the planning board:")
        self.idea_window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
        #print "passed - 4"
        self.idea_window.resize(300, 400)
        self.idea_window.show()

    def show_update_planning_window(self, parent_dictionary):
        self.idea_update_window = AddPlan.PlanUpdateWindow (self, parent_dictionary, self.main_window)
        self.idea_update_window.setWindowTitle("Update the plan:")
        self.idea_update_window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
        #print "passed - 4"
        self.idea_update_window.resize(300, 400)
        self.idea_update_window.show()



class MainForm (QtGui.QWidget):

    def __init__(self, AppManObj, parent = None):

        self.spent = 0
        self.earned = 0
        QtGui.QWidget.__init__(self, parent)
        self.app_man_obj = AppManObj
        #print "passed"
        self.default = {
            'money_limit' : 20000}
        self.tab_bar = QtGui.QTabWidget(self)
        self.group_home = QtGui.QGroupBox(self.tab_bar)
        self.home_current_account = QtGui.QLabel(self.group_home)
        self.home_box = QtGui.QGridLayout(self.tab_bar)

        self.group_action = QtGui.QGroupBox("Planning activity:", self.tab_bar)
        self.group_accounting = QtGui.QGroupBox(self.tab_bar)
        self.tab_bar.addTab(self.group_home, "Dashboard")
        self.tab_bar.addTab(self.group_accounting, "Account")
        self.tab_bar.addTab(self.group_action, "Planning")
        #self.
        self.grid = QtGui.QGridLayout(self.group_action)
        self.btnLogout = QtGui.QPushButton("Quit", self.group_accounting)
        self.vbox = QtGui.QGridLayout(self)
        self.vbox.addWidget(self.tab_bar, 0, 0)
        #self.grid.addWidget(self.commit_label, 0, 0)
        #self.grid.addWidget(self.btnCommit, 1, 0)
        #self.grid.addWidget(self.btnPlanning, 1, 1)
        #self.grid.addWidget(self.planning_label, 0, 1)
        self.group_action.setLayout(self.grid)
        self.setLayout(self.vbox)

        #group home setting up
        self.current_account = QtGui.QLabel(
            "text", self.group_accounting
            )
        self.dash_box = QtGui.QGridLayout()
        #self.dash_box.addWidget(self.current_account, 0, 0)
        self.dash_box.addWidget(self.btnLogout, 3, 3)
        # recent commit history setting up
        self.group_account = QtGui.QGroupBox("Balans", self.group_accounting)
        self.table_model = QtGui.QStandardItemModel(0, 4, self.group_account)
        self.table_model.setHorizontalHeaderLabels(["author", "amount", 'description','date'])
        self.account_box = QtGui.QVBoxLayout(self.group_account)
        self.table = QtGui.QTableView(self.group_account)
        self.table.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch)
        self.table.resizeColumnsToContents()
        self.table.setModel(self.table_model)
        self.account_box.addWidget(self.current_account)
        self.account_box.addWidget(self.table)
        self.group_account.setLayout(self.account_box)
        #commit setting up
        self.group_commit = QtGui.QGroupBox(self.group_accounting)
        self.btnCommit = QtGui.QPushButton("Commit", self.group_commit)
        self.commit_label = QtGui.QLabel(
            "Commit changes in the budget\n(Has a sum of money been spent or earned? \nThen don\'t hesitate and hit the 'Commit' button!)",
            self.group_commit
            )
        self.commit_box = QtGui.QHBoxLayout(self.group_commit)
        self.commit_box.addWidget(self.commit_label)
        self.commit_box.addWidget(self.btnCommit)
        self.group_commit.setLayout(self.commit_box)
        self.dash_box.addWidget(self.group_account, 0, 0)
        self.dash_box.addWidget(self.group_commit, 1, 0)
        self.group_accounting.setLayout(self.dash_box)

        #self.update_dashboard()

        self.home_box.addWidget(self.home_current_account, 0, 0)
        self.group_home.setLayout(self.home_box)

        # recent planning history setting up
        self.group_planning = QtGui.QGroupBox("Plans for this month:", self.group_action)
        self.planning_table_model = QtGui.QStandardItemModel(0, 5, self.group_planning)
        self.planning_table_model.setHorizontalHeaderLabels([
            "author", "minimum price","maximum price", 'description','start date', 'due date'
            ])
        self.planning_box = QtGui    .QGridLayout(self.group_planning)
        self.planning_table = QtGui.QTableView(self.group_planning)
        self.planning_table.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch)
        self.planning_table.resizeColumnsToContents()
        self.planning_table.setModel(self.planning_table_model)
        current_time = self.get_time_interval()
        self.group_filter_dates = QtGui.QGroupBox('Filter', self.group_planning)
        self.filter_box = QtGui.QHBoxLayout(self.group_filter_dates)
        self.filter_date_start = QtGui.QDateEdit(current_time[0], self.group_planning)
        self.filter_date_end = QtGui.QDateEdit(current_time[1], self.group_planning)
        self.btnSearch = QtGui.QPushButton("Search", self.group_filter_dates)
        self.filter_box.addWidget(self.filter_date_start)
        self.filter_box.addWidget(self.filter_date_end)
        self.filter_box.addWidget(self.btnSearch)
        self.group_filter_dates.setLayout(self.filter_box)
        self.plans_total = 0
        self.plans_number = 0
        self.plans_space_left = 0
        self.plans_label = QtGui.QLabel(
            "Total price is: %s\nlist consists of %s items\n%s rub left this month"
            % (self.plans_total, self.plans_number, self.plans_space_left))
        self.planning_box.addWidget(self.plans_label, 0, 0)
        self.planning_box.addWidget(self.group_filter_dates, 2, 0)
        self.planning_box.addWidget(self.planning_table, 3, 0)
        self.group_planning.setLayout(self.planning_box)
        self.grid.addWidget(self.group_planning, 0, 0)
        self.group_planning_action = QtGui.QGroupBox(self.group_action)
        self.planning_action_box = QtGui.QHBoxLayout(self.group_planning_action)
        self.btnPlanning = QtGui.QPushButton("Add an idea!", self.group_planning_action)
        self.planning_label = QtGui.QLabel(
            "Have and idea for shopping?\nAdd it to the planning list!",
            self.group_planning_action
            )
        self.planning_action_box.addWidget(self.btnPlanning)
        self.planning_action_box.addWidget(self.planning_label)
        self.group_planning_action.setLayout(self.planning_action_box)
        self.grid.addWidget(self.group_planning_action, 1, 0)

        self.update_dashboard()

        self.connect(self.planning_table, QtCore.SIGNAL("clicked(const QModelIndex)"), self.update_planning_table)
        self.connect(self.table, QtCore.SIGNAL("clicked(const QModelIndex)"), self.update_table)
        self.connect(self.btnLogout, QtCore.SIGNAL("clicked()"), QtGui.qApp.quit)
        self.connect(self.btnCommit, QtCore.SIGNAL("clicked()"), self.commit_clicked)
        self.connect(self.tab_bar, QtCore.SIGNAL("currentChanged(int)"), self.update_dashboard)
        self.connect(self.btnPlanning, QtCore.SIGNAL('clicked()'), self.add_idea)
        self.connect(self.btnSearch, QtCore.SIGNAL('clicked()'), self.update_planning)

    def update_dashboard (self):
        self.update_general_account()
        self.update_recent_commits()
        self.update_planning()

    def update_planning (self):
        table = ()
        self.app_man_obj.db_session.void_commander(
            query.find_planning_data([
                self.filter_date_start.date().toPyDate(), self.filter_date_end.date().toPyDate()
                ])
                )
        table = self.app_man_obj.db_session.db_cursor.fetchall()
        #print 'table = ' , (table)
        self.raw_planning_table = table
        rows = len(table)
        ##print rows
        self.plans_total = 0
        self.plans_number = 0
        self.plans_space_left = 0
        self.planning_table_model.setRowCount(rows)
        var = ['', '', '', '', '', '']
        if rows > 0:
            for i in range(0, rows):
                var[0] = table[i]['author_name']
                var[4] = table[i]['start_date']
                var[1] = table[i]['price_low']
                var[2] = table[i]['price_high']
                var[3] = table[i]['description']
                var[5] = table[i]['finish_date']
                self.plans_total = self.plans_total + int(var[2])
                self.plans_number = self.plans_number + 1
                for j in [0, 1, 2, 3, 4, 5]:
                    ##print j
                    item = QtGui.QStandardItem(str(var[j]))
                    self.planning_table_model.setItem(i, j, item)
        self.plans_space_left = self.balans - self.plans_total
        today = self.get_time_interval()
        if (
            self.filter_date_start.date().toPyDate() == today[0] and
            self.filter_date_end.date().toPyDate() == today[1]
                ):
            self.plans_label.setText(
                "Total price is: %s\nlist consists of %s items\n%s rub left this month"
                % (self.plans_total, self.plans_number, self.plans_space_left))
        else:
            self.plans_label.setText(
                "Total price is: %s\nlist consists of %s items\n"
                % (self.plans_total, self.plans_number))


    def get_time_interval (self):
        today = date.today()
        if today.month == 12:
            next_month = 1
        else:
            next_month = today.month + 1
        return [date(today.year, today.month, 1), date(today.year, next_month, 1)]

    def update_table (self):
        #print 'update_commit_entered'
        row = self.table.selectedIndexes()[0].row()
        self.app_man_obj.show_commit_update(self.raw_commit_table[row])

    def update_planning_table (self):
        #print 'update_planning_entered'
        row = self.planning_table.selectedIndexes()[0].row()
        self.app_man_obj.show_update_planning_window(self.raw_planning_table[row])

    def update_recent_commits (self):
        ##print "recent commits entered"
        self.app_man_obj.db_session.void_commander(query.dashboard_commits())
        table = self.app_man_obj.db_session.db_cursor.fetchall()
        self.raw_commit_table = table
        rows = len(table)
        ##print rows
        self.table_model.setRowCount(rows)
        var = ['', '', '', '']
        for i in range(0, rows):
            var[0] = table[i]['author_name']
            var[3] = table[i]['date']
            var[1] = table[i]['amount']
            var[2] = table[i]['description']
            if table[i]['flag_value'] == True:
                var[1] = var[1]*(-1)
            ##print "Var = %s" % var
            for j in [0, 1, 2, 3]:
                ##print j
                item = QtGui.QStandardItem(str(var[j]))
                self.table_model.setItem(i, j, item)



    def update_general_account(self):
        ##print "entered update"
        def fetch_data ():
            self.app_man_obj.db_session.void_commander(query.dashboard_account())
            account_table = self.app_man_obj.db_session.db_cursor.fetchall()
            ##print account_table
            return account_table

        table = fetch_data()
        balans = []
        self.earned = 0
        self.spent = 0
        flag = 0
        for itn in range(len(table)):
            ##print itn
            if table[itn]['flag_value'] == 1:
                self.spent = self.spent + table[itn]['amount']
                flag = -1
            else:
                flag = 1
                self.earned = self.earned + table[itn]['amount']
            balans.append(table[itn]['amount'] * flag)
        ##print '::::: ', sum(balans), self.earned, self.spent
        self.balans = sum(balans)
        self.current_account.setText(
            "Total earned: %s\nTotal spent: %s\nOur current balans: %s" %(self.earned, self.spent, self.balans)
            )
        self.home_current_account.setText(
            self.current_account.text()
            )

    def add_idea (self):
        self.app_man_obj.show_add_idea_window()



    def commit_clicked (self):
        #self.cls.close()
        ##print "passed -3"
        self.app_man_obj.show_commit()
        #app_man_obj.db_session.commander("EXIT")
        #QtGui.qApp.quit()

    def closeEvent (self, close_event):
        #self.app_man_obj.db_session.void_commander("EXIT")
        ##print "passed - 5"
        close_event.accept()
        QtGui.qApp.quit()


class CommitWindow (QtGui.QDialog):

    def __init__(self, AppManObj, parent = None):
        self.parent = parent
        QtGui.QDialog.__init__(self, parent)
        self.app_man_obj = AppManObj
        #main layout
        self.default = {
            "amount": '0',
            'date' : self.set_date(),
            'spent' : True,
            'earned' : False,
            'text' : '',
            'link' : 'No link'
            }
        self.grid = QtGui.QGridLayout()
        #first row of the main layout
        self.group_amount = QtGui.QGroupBox("Amount")
        self.amount_edit = QtGui.QLineEdit("0", self.group_amount)
        self.amount_warning_label = QtGui.QLabel(self.group_amount)
        self.amount_warning_label.setVisible(False)
        self.date = QtGui.QDateEdit(self.set_date(), self.group_amount)
        self.amount_box = QtGui.QGridLayout()
        self.amount_box.addWidget(self.amount_warning_label, 0, 0)
        self.amount_box.addWidget(self.amount_edit, 1, 0)
        self.amount_box.addWidget(self.date, 1, 1)
        self.group_amount.setLayout(self.amount_box)
        #second row of the main layout
        self.group_flag = QtGui.QGroupBox("Money is:")
        self.flag_box = QtGui.QVBoxLayout()
        self.rbtnSpent = QtGui.QRadioButton("Spent", self.group_flag)
        self.rbtnEarned = QtGui.QRadioButton("Earned", self.group_flag)
        self.rbtnSpent.setChecked(True)
        self.flag_box.addWidget(self.rbtnSpent)
        self.flag_box.addWidget(self.rbtnEarned)
        self.group_flag.setLayout(self.flag_box)
        #third row of the main layout
        self.description_box = QtGui.QVBoxLayout()
        self.group_description = QtGui.QGroupBox("Description:")
        self.text_edit_warning = QtGui.QLabel(self.group_description)
        self.text_edit_warning.setVisible(False)
        self.text_edit = QtGui.QTextEdit(self.group_description)
        self.description_box.addWidget(self.text_edit_warning)
        self.description_box.addWidget(self.text_edit)
        self.group_description.setLayout(self.description_box)
        # third row - link edit
        self.link_box = QtGui.QVBoxLayout()
        self.group_link = QtGui.QGroupBox()
        self.link_label = QtGui.QLabel("Have a link? Type in here:")
        self.link_edit = QtGui.QLineEdit(self.group_link)
        self.link_edit.setText('No link')
        self.link_box.addWidget(self.link_label)
        self.link_box.addWidget(self.link_edit)
        self.group_link.setLayout(self.link_box)
        #fourth row of the main layout - buttons
        self.group_buttons = QtGui.QGroupBox()
        self.buttons_box = QtGui.QHBoxLayout()
        self.btnClear = QtGui.QPushButton("Clear", self.group_buttons)
        self.btnBack = QtGui.QPushButton("Back", self.group_buttons)
        self.btnSave = QtGui.QPushButton("Save", self.group_buttons)
        self.buttons_box.addWidget(self.btnBack)
        self.buttons_box.addWidget(self.btnClear)
        self.buttons_box.addWidget(self.btnSave)
        self.group_buttons.setLayout(self.buttons_box)
        self.grid.addWidget(self.group_amount, 0, 0)
        self.grid.addWidget(self.group_flag, 1, 0)
        self.grid.addWidget(self.group_description, 2, 0)
        self.grid.addWidget(self.group_link, 2, 1)
        #self.grid.addWidget(self.btnBack, 3, 0)
        self.grid.addWidget(self.group_buttons, 3, 1)
        self.setLayout(self.grid)
        self.setWindowModality(QtCore.Qt.WindowModal)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
        self.connect(self.btnSave, QtCore.SIGNAL("clicked()"), self.check_data)
        self.connect(self.btnClear, QtCore.SIGNAL("clicked()"), self.clear_data)
        self.connect(self.btnBack, QtCore.SIGNAL("clicked()"), self.back_home)

    def set_date (self):
        return date.today()

    def flag_selection (self):
        if self.rbtnSpent.checked() == True:
            return True
        else: return False

    def check_data (self):

        ##print "entered check"

        def input_is_numeric (amount):
            i = 0
            length = len(amount)
            while i < length:
                if amount[i] not in ['1', '2','3', '4', '5', '6', '7', '8', '9', '0']:
                    return False
                i = i + 1
                ###print 'i = %s' % i
            return True

        amount = str(self.amount_edit.text())
        text_passed = False
        amount_passed = False
        text = str(self.text_edit.toPlainText())
        #check = (amount != self.default['amount']) + (text != self.default['text'])
        if amount != self.default['amount']:

                if len(amount) > 7:
                    if not input_is_numeric(amount):
                        self.amount_warning_label.setText(
                            "*Be a realist,\namount cannot be longer than 7 digits.\n*The field accepts only numbers from 0 to 9"
                            )
                        amount_passed = False
                        if not self.amount_warning_label.isVisible:
                             self.amount_warning_label.setVisible(True)
                    else :
                        self.amount_warning_label.setText(
                        "*Be a realist, ammount cannot be longer than 7 digits."
                        )
                        amount_passed = False
                        if not self.amount_warning_label.isVisible:
                            self.amount_warning_label.setVisible(True)
                elif not input_is_numeric(amount):
                    self.amount_warning_label.setText(
                        "*The field accepts only numbers from 0 to 9"
                        )
                    amount_passed = False
                    if not self.amount_warning_label.isVisible():
                        self.amount_warning_label.setVisible(True)
                else:
                    if self.amount_warning_label.isVisible:
                        self.amount_warning_label.setVisible(False)
                    amount_passed = True

        else :
            self.amount_warning_label.setText("*Please enter an amount to be commited")
            amount_passed = False
            if not self.amount_warning_label.isVisible():
                self.amount_warning_label.setVisible(True)
        if (text != self.default['text']):
            ###print text, len(text)
            if len(text) > 30:
                self.text_edit_warning.setText(
                    "*Text cannot be longer than 30 characters \n(%s characters now)" %len(text)
                    )
                text_passed = False
                if not self.text_edit_warning.isVisible():
                     self.text_edit_warning.setVisible(True)
            else:
                if self.text_edit_warning.isVisible():
                     self.text_edit_warning.setVisible(False)
                text_passed = True

        else:
            self.text_edit_warning.setText(
                "*Please enter description"
                )
            text_passed = False
            if not self.text_edit_warning.isVisible():
                self.text_edit_warning.setVisible(True)

        if str(self.link_edit.text()) == '':
            self.link_edit.setText(self.default['link'])
        ##print text_passed, "  ", amount_passed
        if text_passed and amount_passed:
            self.save_data()



    def save_data (self):
        ##print "entered save"
        values = []
        if self.app_man_obj.db_session.verbose_commander(
            query.update_actions(self.app_man_obj.db_session.username)
            ):
            self.app_man_obj.db_session.void_commander(
                query.extract_from_actions(self.app_man_obj.db_session.username)
                )
        else:
            QtGui.qApp.quit()
        last_event = self.app_man_obj.db_session.db_cursor.fetchall()
        ##print last_event
        values = [
            last_event[0]['event_id'],
            str(self.amount_edit.text()),
            self.date.date().toPyDate(),
            self.rbtnSpent.isChecked(),
            str(self.text_edit.toPlainText()),
            str(self.link_edit.text())
            ]
        ##print values
        ##print "date is: %s" % self.date.date().toPyDate()
        self.app_man_obj.db_session.void_commander(
            query.commit(values)
            )
        self.app_man_obj.db_session.db_cursor.connection.commit()
        self.clear_data()
        self.parent.update_dashboard()


    def clear_data (self):
        ##print "entered clear"
        self.amount_edit.setText(self.default['amount'])
        self.amount_warning_label.setVisible(False)
        self.date.setDate(self.set_date())
        self.text_edit.setText(self.default['text'])
        self.text_edit_warning.setVisible(False)
        self.link_edit.setText(self.default['link'])
        self.rbtnSpent.setChecked(True)

    def back_home (self):
        ##print "back home entered"
        self.close()


class UpdateCommitWindow(CommitWindow):

    def __init__(self, AppManObj, parent_dic, parent = None):
        CommitWindow.__init__(self, parent)
        self.parent = parent
        self.parent_dic = parent_dic
        self.app_man_obj = AppManObj
        print "Herer is the received parent dictionary: ", parent_dic
        ##print parent_dic
        self.default = {
            "amount": '0',
            'inherited_amount' : str(parent_dic['amount']),
            'date' : parent_dic['date'],
            'spent' : parent_dic['flag_value'],
            'text' : '',
            'inherited_text' : str(parent_dic['description']),
            'link' : parent_dic['url'],
            'parent_id' : parent_dic['event']
            }
        self.amount_edit.setText(self.default['inherited_amount'])
        self.date.setDate(self.default['date'])
        self.text_edit.setText(self.default['inherited_text'])
        self.link_edit.setText(self.default['link'])
        if self.default['spent']:
            self.rbtnSpent.setChecked(True)
        else:
            self.rbtnEarned.setChecked(True)
        self.btnDelete = QtGui.QPushButton('Delete', self.group_buttons)
        self.buttons_box.addWidget(self.btnDelete)

        self.connect(self.btnDelete, QtCore.SIGNAL("clicked()"), self.delete_line)

    def delete_line (self):

        self.app_man_obj.db_session.void_commander(
            query.disable_commit(self.default['parent_id'])
            )
        self.parent.update_dashboard()
        self.close()

    def save_data (self):
        ###print "entered save updated commit"
        values = []
        self.app_man_obj.db_session.void_commander(
            query.update_actions(self.app_man_obj.db_session.username, self.default['parent_id'])
            )
        self.app_man_obj.db_session.void_commander(
            query.extract_from_actions(self.app_man_obj.db_session.username)
            )
        last_event = self.app_man_obj.db_session.db_cursor.fetchall()
        ###print last_event
        values = [
            last_event[0]['event_id'],
            str(self.amount_edit.text()),
            self.date.date().toPyDate(),
            self.rbtnSpent.isChecked(),
            str(self.text_edit.toPlainText()),
            str(self.link_edit.text())
            ]
        ###print values
        ###print "date is: %s" % self.date.date().toPyDate()
        self.app_man_obj.db_session.void_commander(
            query.commit(values)
            )
        self.app_man_obj.db_session.void_commander(
            query.disable_commit(self.default["parent_id"])
            )
        self.app_man_obj.db_session.db_cursor.connection.commit()
        # self.clear_data()
        self.parent.update_dashboard()
        self.close()





if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    app_man_obj = AppManager(app)
    app_man_obj.show_login()
    sys.exit(app.exec_())




